"""
AI助手API视图
"""
from rest_framework.views import APIView
from rest_framework.decorators import api_view
from apps.positions.models import Position
from utils.response import success_response, error_response
from .kimi_client import KimiClient
from .prompts import PromptTemplates


class JobRecommendationView(APIView):
    """岗位推荐API"""
    
    def post(self, request):
        """
        智能岗位推荐
        
        Request Body:
            {
                'skills': ['Java', 'Spring', 'MySQL'],
                'experience': '3-5年',
                'education': '本科',
                'cities': ['北京', '上海'],
                'salary_range': '20-30k'
            }
        
        Returns:
            AI推荐结果
        """
        # 获取用户输入
        skills = request.data.get('skills', [])
        experience = request.data.get('experience', '')
        education = request.data.get('education', '')
        cities = request.data.get('cities', [])
        salary_range = request.data.get('salary_range', '')
        
        # 根据用户条件查询匹配的岗位（取Top 10）
        positions = Position.objects.filter(salary_avg__isnull=False)
        
        if cities:
            positions = positions.filter(city__in=cities)
        if education:
            positions = positions.filter(education=education)
        if experience:
            positions = positions.filter(work_year=experience)
        
        positions = positions.order_by('-salary_avg')[:10]
        
        # 构建岗位数据字符串
        job_data_str = '\n\n'.join([
            f"【{i+1}】{pos.position_name} - {pos.company_full_name}\n"
            f"地点：{pos.city}\n"
            f"薪资：{pos.salary}\n"
            f"要求：{pos.education} | {pos.work_year}\n"
            f"优势：{pos.position_advantage or '未说明'}"
            for i, pos in enumerate(positions)
        ])
        
        if not job_data_str:
            return error_response(message='未找到匹配的岗位', code=404)
        
        # 调用Kimi API
        client = KimiClient()
        system_prompt, user_prompt = PromptTemplates.job_recommendation(
            user_skills=skills,
            user_experience=experience,
            user_education=education,
            user_cities=cities,
            user_salary=salary_range,
            job_data=job_data_str
        )
        
        reply, error = client.simple_chat(user_prompt, system_prompt)
        
        if error:
            return error_response(message=f'AI服务异常：{error}', code=500)
        
        return success_response(data={'recommendation': reply}, message='生成推荐成功')


class CareerPlanningView(APIView):
    """职业规划API"""
    
    def post(self, request):
        """
        职业发展规划
        
        Request Body:
            {
                'current_position': 'Java初级开发',
                'target_position': 'Java架构师'
            }
        
        Returns:
            AI规划建议
        """
        current_position = request.data.get('current_position', '')
        target_position = request.data.get('target_position', '')
        
        if not current_position or not target_position:
            return error_response(message='请提供当前职位和目标职位', code=400)
        
        # 查询目标岗位的市场数据
        target_jobs = Position.objects.filter(
            position_name__icontains=target_position.split()[0]  # 简单匹配
        )[:5]
        
        market_data_str = '\n'.join([
            f"- {job.position_name}：{job.salary} | {job.work_year} | {job.education}"
            for job in target_jobs
        ]) if target_jobs else '暂无市场数据参考'
        
        # 调用Kimi API
        client = KimiClient()
        system_prompt, user_prompt = PromptTemplates.career_planning(
            current_position=current_position,
            target_position=target_position,
            market_data=market_data_str
        )
        
        reply, error = client.simple_chat(user_prompt, system_prompt)
        
        if error:
            return error_response(message=f'AI服务异常：{error}', code=500)
        
        return success_response(data={'plan': reply}, message='生成规划成功')


class JobInterpretationView(APIView):
    """职位解读API"""
    
    def post(self, request):
        """
        职位描述解读
        
        Request Body:
            {
                'position_id': 123
            }
            或
            {
                'job_description': '...',
                'job_requirements': '...'
            }
        
        Returns:
            AI解读结果
        """
        position_id = request.data.get('position_id')
        
        if position_id:
            # 从数据库获取职位信息
            try:
                position = Position.objects.get(id=position_id)
                job_description = position.position_detail or ''
                job_requirements = f"{position.education} | {position.work_year} | {position.salary}"
            except Position.DoesNotExist:
                return error_response(message='职位不存在', code=404)
        else:
            # 使用用户提供的描述
            job_description = request.data.get('job_description', '')
            job_requirements = request.data.get('job_requirements', '')
        
        if not job_description:
            return error_response(message='请提供职位描述', code=400)
        
        # 调用Kimi API
        client = KimiClient()
        system_prompt, user_prompt = PromptTemplates.job_interpretation(
            job_description=job_description,
            job_requirements=job_requirements
        )
        
        reply, error = client.simple_chat(user_prompt, system_prompt)
        
        if error:
            return error_response(message=f'AI服务异常：{error}', code=500)
        
        return success_response(data={'interpretation': reply}, message='解读成功')

